package top.zaixia.game.deployment.filter

import jakarta.servlet.FilterChain
import jakarta.servlet.http.HttpServletRequest
import jakarta.servlet.http.HttpServletResponse
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken
import org.springframework.security.core.authority.SimpleGrantedAuthority
import org.springframework.security.core.context.SecurityContextHolder
import org.springframework.stereotype.Component
import org.springframework.web.filter.OncePerRequestFilter
import top.zaixia.game.util.bean.JwtUtil

@Component
class JwtFilter(
  private val jwtUtil: JwtUtil,
) : OncePerRequestFilter() {
	/**
	 * 拦截器
	 */
	override fun doFilterInternal(
	  request: HttpServletRequest,
	  response: HttpServletResponse,
	  filterChain: FilterChain,
	) {
		val token = request.getHeader("Authorization")
		if (token == null || !jwtUtil.isValid(token)){
			response.status = HttpServletResponse.SC_UNAUTHORIZED
			response.contentType = "application/json;charset=UTF-8"
			response.writer.write("""{"error":"Unauthorized","message":"JWT token is missing or invalid"}""")
			return
		}
		
		val userId = jwtUtil.parseToken(token) // 可以添加角色信息，这里暂时示例一个默认角色
		val authorities = listOf(
		  SimpleGrantedAuthority("USER"),
		  SimpleGrantedAuthority("ADMIN")
		) // 构建认证对象并放入 SecurityContext
		SecurityContextHolder.getContext().authentication = UsernamePasswordAuthenticationToken(
		  userId, null, authorities
		)
		
		filterChain.doFilter(request, response)
	}
}